package problem;

import datastruct.tree.BinarySearchTree;

import java.util.*;

/**
 * @author RunningShrimp
 * @date 2021/5/16  18:07
 * @see <a href="https://leetcode-cn.com/problems/binary-tree-level-order-traversal/description/">102. 二叉树的层序遍历</a>
 */
public class BreadthTraversal {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> numList = new ArrayList<>();
        if (root == null) {
            return numList;
        }

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> nums = new ArrayList<>();
            int queueSize = queue.size();
            for (int i = 0; i < queueSize; i++) {
                TreeNode node = queue.poll();
                nums.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }

            numList.add(nums);
        }
        return numList;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
